package com.example.shiro.core.session;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import javax.servlet.ServletRequest;
import java.io.Serializable;

/**
 * @author lijilong
 * @version 1.0
 * @Description:
 * @CreateDate 2018/8/11 14:01
 */
public class CustomSessionManager extends DefaultWebSessionManager {

    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Session session = null;
        Serializable sessionId = getSessionId(sessionKey);
        ServletRequest request = null;
        if(sessionKey instanceof WebSessionKey){
            request = ((WebSessionKey) sessionKey).getServletRequest();
        }
        if(request != null && sessionId != null){
            // 从request中取出session
            session = (Session) request.getAttribute(sessionId.toString());
            if(session == null){
                // request中没有session，查询redis
                session = super.retrieveSession(sessionKey);
                // session放入request
                request.setAttribute(sessionId.toString(), session);
            }
        }
        return session;
    }
}
